<template>
    <div class="common-container">
        <div class="header">
            <div class="header_left">
                <!-- <el-input v-model="tenantName" clearable @clear="nameClear" placeholder="请输入维保组名称" size="small"
                    style="width: 220px" maxlength="20">
                    <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
                        @click="searchClick"></el-button></el-input> -->

                <el-select size="small" style="width: 190px;margin-left: 15px;" @change="changeOrgId" clearable
                    @keyup.enter.native='searchList' v-loadMore="loadMore" v-model='selectedValue' placeholder='请选择组织机构'
                    filterable remote :remote-method="remoteMethod"  @clear="handleClear">
                    <el-option v-for='item in projectList' :label='item.orgName' :value='item.id' :key='item.id'>
                    </el-option>
                    <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"> </div>
                </el-select>

            </div>
            <div class="header_right">
                <el-button class="el_button" size="small" icon="el-icon-plus" style="margin-left: 15px" @click="addClick" v-permission="{ action: 'subscribe:add' }">
                    新增
                </el-button>
            </div>
        </div>
        <div class="content">
            <el-table :data="dataList" class="table" :header-cell-style="headerStyle">
                <el-table-column align="center" label="序号" type="index" width="80" height="30"></el-table-column>

                <el-table-column align="center" prop="orgName" label="组织机构" min-width="90"
                    show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="url" label="URL" min-width="100"
                    show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="event" label="事件类型" min-width="90" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.event == 1" type="warning">设备状态更新</el-tag>
                        <el-tag v-else-if="scope.row.event == 2" type="success">告警事件</el-tag>
                        <el-tag v-else-if="scope.row.event == 3" type="success">绑定事件</el-tag>
                        <el-tag v-else-if="scope.row.event == 4" type="danger">解绑事件</el-tag>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="event" label="订阅开关" min-width="70" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-switch v-model.trim="scope.row.swit" active-color="#7367F0" inactive-color="#C0CCDA"
                            @change="switchChange(scope.row)" :active-value="1" :inactive-value="0">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="createTime" label="创建时间" min-width="150"
                    show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="操作" min-width="140">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="推送" placement="bottom" v-if="scope.row.event == 3" v-permission="{ action: 'subscribe:push' }">
                            <i @click="pushClick(scope.row.id)" class="el-icon-position tableBtnIcon"></i>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom" v-permission="{ action: 'subscribe:edit' }">
                            <i @click="editClick(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="bottom" v-permission="{ action: 'subscribe:delete' }">
                            <i @click="delClick(scope.row.id)" class="iconfont shanchu tableBtnIcon"></i>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit"
                :pageSizes="[10, 20, 30, 50]" @pagination="getDataList" class="pagination" />
        </div>

        <addProtectConfig ref="refaddProtectConfig"></addProtectConfig>
        <editProtectConfig ref="refeditProtectConfig" :editData="editData"></editProtectConfig>

    </div>
</template>
  
<script>
import { reqSubscribePage, reqSubscribeRemove, reqOrgList, reqSubscribepush, reqSubscribeUpdate } from "@api/api.js";
import Pagination from "@components/Pagination.vue";
import tableStyleMixin from "@mixin/table-style";
import addProtectConfig from "./components/addProtectConfig.vue";
import editProtectConfig from "./components/editProtectConfig.vue";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";

export default {
    name: "tenant",
    components: { Pagination, addProtectConfig, editProtectConfig },
    mixins: [tableStyleMixin, loadMore],
    data() {
        return {
            tenantName: "",
            loadingSearch: false, //查询按钮loading
            dataList: [],
            limit: 10,
            page: 1,
            total: 0,
            targetId: "",
            editData: {
            }, //修改数据

            projectList: [], //组织机构
            sysInstanceIndex: 1,
            sysInstanceTotalPages: 10,
            loading: false,
            orgName: '',
            selectedValue:""
        };
    },
    computed: {
        ...mapState(["user"]),
    },
    async created() {
        console.log(123)
        await this.OrgList(true);
        await this.getDataList();
    },
    mounted() { },
    methods: {
        // 清空
        handleClear() {
            this.selectedValue = ''; 
            this.orgName = '';
            this.sysInstanceIndex = 1;
            this.sysInstanceTotalPages = 10;
            this.projectList = []
            this.OrgList()
        },
        // 远程搜索
        async remoteMethod(query) {
            this.selectedValue = query //保留输入的值
            this.orgName = query;
            this.sysInstanceIndex = 1;
            this.sysInstanceTotalPages = 10;
            this.projectList = []
            this.OrgList()
        },
        // 选择组织机构
        changeOrgId(e) {
            this.targetId =e
            this.page = 1;
            this.limit = 10;
            this.getDataList();
        },

        async loadMore() {
            if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10)) return
            this.sysInstanceIndex++
            this.loading = true;
            // 获取列表数据的方法
            await this.OrgList()
            this.loading = false;
        },
        // 获取组织机构
        async OrgList(flag) {
            var res = await reqOrgList( {
                userId: this.user.userId,
                roleName: this.user.roleName,
                tenantId: this.user.tenantId,
                orgName: this.orgName
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.projectList = res.data.rows
        },

        // 获取列表
        async getDataList() {
            const res = await reqSubscribePage(this.page, this.limit, {
                // name: this.tenantName,
                tenantId: this.user.tenantId,
                targetId: this.targetId
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.dataList = res.data.rows;
            this.total = res.data.total;
        },
        // 搜索
        async searchClick() {
            this.page = 1;
            this.limit = 10;
            this.loadingSearch = true;
            await this.getDataList();
            this.loadingSearch = false;
        },
        getInitDataList() {
            this.page = 1;
            this.limit = 10;
            this.getDataList();
        },
        // 清除请求
        nameClear() {
            this.getInitDataList();
        },
        // 新增
        addClick() {
            this.$refs.refaddProtectConfig.dialogVisible = true;
            this.$refs.refaddProtectConfig.OrgList(true)
        },
        // 编辑
        editClick(row) {
            // console.log(row);
            this.editData = JSON.parse(JSON.stringify(row));
            this.$refs.refeditProtectConfig.dialogVisible = true;
        },
        // 删除
        async delClick(id) {
            const result = await this.$confirm(
                "此操作将永久删除该订阅配置, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch(() => { });
            if (result !== "confirm") return;
            const res = await reqSubscribeRemove(id);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("删除成功");
            this.getInitDataList();
        },
        // 推送
        async pushClick(id) {
            const result = await this.$confirm(
                "此操作将推送订阅配置, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch(() => { });
            if (result !== "confirm") return;
            const res = await reqSubscribepush(id);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("推送成功");
            this.getInitDataList();
        },
        switchChange(row) {
            console.log(row);
            if (row.swit == 1) {
                this.$confirm("此操作将开启订阅, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        let res = await reqSubscribeUpdate(row);
                        if (res.code !== 20000) {
                            this.$modal.notifyWarning(res.message);
                            row.swit = 0;
                            return
                        }
                        row.swit = 1;
                        this.$modal.notifySuccess("开启订阅成功");
                    })
                    .catch(() => {
                        row.swit = 0;
                    });
            } else {
                this.$confirm("此操作将关闭订阅, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        let res = await reqSubscribeUpdate(row);
                        if (res.code !== 20000) {
                            this.$modal.notifyWarning(res.message);
                            row.swit = 1;
                            return
                        }
                        row.swit = 0;
                        this.$modal.notifySuccess("关闭订阅成功");
                    })
                    .catch(() => {
                        row.swit = 1;
                    });
            }
        },
    },
};
</script>
  
<style scoped lang="less">
@import url("~@views/style/tablePage.less");

::v-deep .el_button.el-button--small {
    background: #7367f0;
    color: #fff;
    border: none;
}

// 下拉框加载开始
.div_box {
    height: 276px;
    position: absolute;
    top: -1px;
    left: -1px;
    width: 100%;
    z-index: 9999;
    // background: red;
    // opacity: 0.5;
}

::v-deep .el-loading-mask {
    border-radius: 4px;
}

// 下拉框加载结束
</style>
  